package com.xiaoxi.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSON;
import com.xiaoxi.yygh.hosp.repository.HospitalRepository;
import com.xiaoxi.yygh.hosp.service.HospitalService;
import com.xiaoxi.yygh.model.hosp.Hospital;
import com.xiaoxi.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {
    
    @Autowired
    private HospitalRepository hospitalRepository;


    @Override
    public void save(Map<String, Object> paramMap) {
        // 将参数map转换成Hospital
        String stringMap = JSON.toJSONString(paramMap);
        Hospital hospital = JSON.parseObject(stringMap, Hospital.class);
        
        // 查询db里是否存在数据
        
        Hospital hospitalExist = hospitalRepository.getHospitalByHoscode(hospital.getHoscode());
        
        if (hospitalExist != null){
            // 有，修改
            hospital.setStatus(hospital.getStatus());
            hospital.setCreateTime(hospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);

            hospitalRepository.save(hospital);
        }else {
            // 没有，添加
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public Hospital getByHoscode(String hoscode) {

        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        return hospital;
    }

    // 医院列表(条件查询分页)
    @Override
    public Page<Hospital> selectHospPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Pageable pageable = PageRequest.of(page - 1, limit);

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        
        Hospital hospital = new Hospital();

        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        
        Example<Hospital> example = Example.of(hospital, matcher);

        Page<Hospital> all = hospitalRepository.findAll(example, pageable);

        return all;
    }
}
